//
//  QLPublishLifeInvitatVC.m
//  神约
//
//  Created by qlwl on 17/2/8.
//  Copyright © 2017年 qlwl. All rights reserved.
//

#import "QLPublishLifeInvitatVC.h"
#import "QLPublishLifeInvitatCell.h"
#import "QLPublishSetPriceVC.h"
#import "UIAlertController+AlertController.h"
#import "QLDatePickerView.h"
#import "AddressPicker.h"
#import "QLPublishLifeDataModel.h"
#import "NSDate+time.h"
#import "UIView+FrameKIt.h"
#import "UIView+Frame.h"

@interface QLPublishLifeInvitatVC ()<UITableViewDelegate,UITableViewDataSource,PickerViewDataSource, PickerViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) QLDatePickerView * datePicker; //
@property (nonatomic, strong) AddressPicker * timePicker1; // 时间picker
@property (nonatomic, strong) AddressPicker * timePicker2; // 时间picker
@property (nonatomic, strong) AddressPicker * timePicker; //
@property (nonatomic, strong) QLPublishLifeDataModel * dataModel; //

@end

@implementation QLPublishLifeInvitatVC
{
    
    NSArray * _timeArray;
    NSMutableArray * _timeArray1;
    NSArray * _otherPayArray;
    int _selectRow;
    int _selectRow1;
    int _selectRow2;
    float _imaCellHeight;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _imaCellHeight = 1;
    _timeArray = @[@"今天",@"周一到周五",@"周末约",@"随时可约",@"其他时间..."];
    _timeArray1 = [[NSMutableArray alloc] init];
    for (int i =0 ; i < 24; i++) {
        [_timeArray1 addObject:[NSString stringWithFormat:@"%02d:00",i]];
    }
    [self netOtherPayTypeWorking];
}

#pragma mark TabDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        if (self.dataModel.isPay) {
            return 3;
        }
        return 3;
    }else if (section == 2){
        return 4;
    }else if (section == 3){
        return 2;
    }else if (section == 4){
        return 2;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        QLPublishLifeInvitatCell * cell = [tableView dequeueReusableCellWithIdentifier:@"QLPublishLifeInvitatCell"];
        cell.titLab.text = @"邀约内容";
        cell.textField.text = self.dataModel.invitatTit;
        cell.textField.enabled = NO;
        return cell;
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            QLPublishLifeInvitatCell * cell = [tableView dequeueReusableCellWithIdentifier:@"QLPublishLifeInvitatCell"];
            cell.titLab.text = @"收费类型";
            cell.textField.text = self.dataModel.isPay?@"收费":@"免费";
            cell.textField.enabled = NO;
            return cell;
        }else if (indexPath.row == 1){
            QLPublishLifeInvitatCell * cell = [tableView dequeueReusableCellWithIdentifier:@"QLPublishLifeInvitatCell"];
            cell.titLab.text = @"服务价格";
            cell.textField.placeholder = @"填写服务价格10~1000之间";
            cell.textField.enabled = YES;
            cell.contentEditChanged = ^(NSString * price){
                self.dataModel.price = price;
            };
            return cell;
        }else if (indexPath.row == 2){
            QLPublishLifeInvitatCell * cell = [tableView dequeueReusableCellWithIdentifier:@"QLPublishLifeInvitatCell"];
            cell.titLab.text = @"可接受时常";
            cell.textField.placeholder = @"1~10小时";
            cell.textField.enabled = YES;
            cell.contentEditChanged = ^(NSString * time){
                self.dataModel.acceptableHours = time;
            };
            return cell;
        }
    }else if (indexPath.section == 2){
        QLPublishLifeInvitatCell2 * cell = [tableView dequeueReusableCellWithIdentifier:@"QLPublishLifeInvitatCell2"];
        NSArray * titArray = @[@"目的地",@"时间范围",@"其他消费",@"性别要求"];
        cell.titLab.text = titArray[indexPath.row];
        NSArray * placeArray = @[@"选择地点",@"选择时间",@"选择消费类型",@"选择性别"];
        cell.textField.placeholder = placeArray[indexPath.row];
        if (indexPath.row == 0) {
            cell.textField.text = self.dataModel.address;
        }else if (indexPath.row == 1){
            cell.textField.text = self.dataModel.time;
        }else if (indexPath.row == 2){
            cell.textField.text = self.dataModel.otherPay;
        }else if (indexPath.row == 3){
            cell.textField.text = self.dataModel.sex;
        }
        return cell;
    }else if (indexPath.section == 3){
        QLPublishLifeInvitatCell3 * cell = [tableView dequeueReusableCellWithIdentifier:@"QLPublishLifeInvitatCell3"];
        NSArray * titArray = @[@"可以接送女方",@"女方可带1名好友"];
        cell.titLab.text = titArray[indexPath.row];
        if (indexPath.row == 0) {
            cell.selectBtn.selected = self.dataModel.canShuttleWoman;
        }else{
            cell.selectBtn.selected = self.dataModel.womanTakeFriend;
        }
        cell.selectBtnClick = ^(BOOL select){
            if (indexPath.row == 0) {
                self.dataModel.canShuttleWoman = select;
            }else{
                self.dataModel.womanTakeFriend = select;
            }
        };
        return cell;
    }else if (indexPath.section == 4){
        if (indexPath.row == 0) {
            QLPublishLifeInvitatCell4 * cell = [tableView dequeueReusableCellWithIdentifier:@"QLPublishLifeInvitatCell4"];
            cell.textView.text = self.dataModel.remark;
            cell.contentChanged = ^(NSString * content){
                self.dataModel.remark = content;
            };
            return cell;
        }else{
            QLPublishLifeInvitatCell5 * cell = [tableView dequeueReusableCellWithIdentifier:@"QLPublishLifeInvitatCell5"];
            cell.titLab.text = @"添加图片";
            cell.imaArray = self.dataModel.imaArray;
            cell.addImaClick = ^{
                //添加图片
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet andCancelAction:^{
                    
                } andOtherAction:^(int tag) {
                    [self selectImaWithType:2+tag];
                } cancelButtonTitle:@"取消" otherButtonTitles:@"相机",@"相册",nil];
                [self presentViewController:alert animated:YES completion:nil];
            };
            cell.imaClick = ^(NSInteger index){
                
            };
            typeof(cell)t_cell = cell;
            cell.deleteBtnClick = ^(NSInteger index){
                //删除照片
                if (self.dataModel.imaArray.count>index) {
                    [self.dataModel.imaArray removeObjectAtIndex:index];
                }
                [t_cell.collectionView reloadData];
            };
            _imaCellHeight = cell.b_h;
            return cell;
        }
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 1 && indexPath.row == 1){
        if (!self.dataModel.isPay) {
            return 0;
        }
    }
    if (indexPath.section == 4 && indexPath.row == 1) {
        return _imaCellHeight;
    }else if (indexPath.section == 4 && indexPath.row == 0){
        return 100;
    }
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 26;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"基本信息";
    }else if (section == 1){
        return @"邀约费用";
    }else if (section == 2){
        return @"详细信息";
    }else if (section == 3){
        return @"其他要求";
    }else if (section == 4){
        return @"备注说明";
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1 && indexPath.row == 1) {
        QLPublishSetPriceVC * priceVC = [NSString instantiateViewControllerWithIdentifier:@"QLPublishSetPriceVC" andSBName:@"Home"];
        [self.navigationController pushViewController:priceVC animated:YES];
    }
    if (indexPath.section == 2 && indexPath.row == 1) {
//        [self.datePicker showInWindow];
        if (!self.timePicker.isShow) {
            [self.view endEditing:YES];
            [self.timePicker showInView:self.view];
        }else{
            [self.timePicker remove];
        }
    }
    if (indexPath.section == 2 && indexPath.row == 2) {
        
        NSMutableArray * titArray = [NSMutableArray array];
        for (QLPublishLifeOtherPayModel * payModel in _otherPayArray) {
            [titArray addObject:payModel.name];
        }
        
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet andCancelAction:^{
            
        } andOtherAction:^(int tag) {
            QLPublishLifeOtherPayModel * payModel = _otherPayArray[tag];
            self.dataModel.otherPay = payModel.name;
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        } cancelButtonTitle:@"取消" otherButtonInArray:titArray];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
    if (indexPath.section == 2 && indexPath.row == 3) {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet andCancelAction:^{
            
        } andOtherAction:^(int tag) {
            self.dataModel.sex = @[@"女",@"男",@"男女不限"][tag];
            self.dataModel.sexType = tag ;
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        } cancelButtonTitle:@"取消" otherButtonTitles:@"女",@"男",@"男女不限",nil];
        
        
        [self presentViewController:alert animated:YES completion:nil];
    }
    
}
#pragma mark addIma
- (void)finishImagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info andType:(PickerControllerSourceType)type andMediaURL:(NSURL *)url
{
    UIImage * ima = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    [self.dataModel.imaArray addObject:ima];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationNone];
}
- (void)failImagePickerControllerDidCancel:(UINavigationController*)picker
{
    
}


#pragma mark  property
- (QLPublishLifeDataModel *)dataModel
{
    if (!_dataModel) {
        _dataModel = [[QLPublishLifeDataModel alloc] init];
        _dataModel.isPay = self.isPay;
        _dataModel.invitatTit = self.name;
        _dataModel.address = @"金星路24号";
    }
    return _dataModel;
}


- (QLDatePickerView *)datePicker
{
    if (!_datePicker) {
        _datePicker = [QLDatePickerView DatePickerView];
        _datePicker.title = @"选择日期";
        //_datePicker.datePickerMode = UIDatePickerModeTime;
        _datePicker.minimumDate = [NSDate date];
        //_datePicker.maximumDate =
        typeof(self)t_self = self;
        _datePicker.finishBtnClick = ^(NSDate *date){
            t_self.dataModel.time = [date getMyDateStrWithDateFormat:@"YYYY-MM-dd"];
            [t_self.view endEditing:YES];
            [t_self.timePicker1 showInView:t_self.view];
        };
    }
    return _datePicker;
}
//- (QLDatePickerView *)timePicker1
//{
//    if (!_timePicker1) {
//        _timePicker1 = [QLDatePickerView DatePickerView];
//        //_datePicker.datePickerMode = UIDatePickerModeTime;
//        //_datePicker.maximumDate =
//        _timePicker1.title = @"开始时间";
//        typeof(self)t_self = self;
//        _timePicker1.datePickerMode = UIDatePickerModeTime;
//        _timePicker1.finishBtnClick = ^(NSDate *date){
//            t_self.timePicker2.minimumDate = date;
//            t_self.timePicker2.date = date;
//            [t_self.timePicker2 showInWindow];
//        };
//    }
//    return _timePicker1;
//}
//- (QLDatePickerView *)timePicker2
//{
//    if (!_timePicker2) {
//        _timePicker2 = [QLDatePickerView DatePickerView];
//        _timePicker2.title = @"结束时间";
//        //_datePicker.datePickerMode = UIDatePickerModeTime;
//        //_datePicker.maximumDate =
//        typeof(self)t_self = self;
//        _timePicker2.datePickerMode = UIDatePickerModeTime;
//        _timePicker2.finishBtnClick = ^(NSDate *date){
//            
//        };
//    }
//    return _timePicker2;
//}
- (AddressPicker *)timePicker1
{
    if (!_timePicker1) {
        _timePicker1 = [AddressPicker addressPickerView];
        _timePicker1.delegate = self;
        _timePicker1.dataSource = self;
        _timePicker1.isLoding = NO;
        [_timePicker1 setTopHeadColor:NavBarTintColor];
        [_timePicker1 setTopTitle:@"开始时间"];
        [_timePicker1 setTopTitleColor:[UIColor whiteColor]];
        [_timePicker1 setSureOrCancelBtnColor:[UIColor whiteColor]];
        _timePicker1.bgColor = [UIColor clearColor];
        typeof(self) t_self = self;
        _timePicker1.sureBtnClick = ^{
            t_self.dataModel.beginTime = _timeArray1[_selectRow1];
            [t_self.view endEditing:YES];
            [t_self.timePicker2 showInView:t_self.view];
        };
    }
    return _timePicker1;
}
- (AddressPicker *)timePicker2
{
    if (!_timePicker2) {
        _timePicker2 = [AddressPicker addressPickerView];
        _timePicker2.delegate = self;
        _timePicker2.dataSource = self;
        _timePicker2.isLoding = NO;
        [_timePicker2 setTopHeadColor:NavBarTintColor];
        [_timePicker2 setTopTitle:@"结束时间"];
        [_timePicker2 setTopTitleColor:[UIColor whiteColor]];
        [_timePicker2 setSureOrCancelBtnColor:[UIColor whiteColor]];
        _timePicker2.bgColor = [UIColor clearColor];
        typeof(self) t_self = self;
        _timePicker2.sureBtnClick = ^{
            t_self.dataModel.endTime = _timeArray1[_selectRow2];
            t_self.dataModel.time = [NSString stringWithFormat:@"%@ %@~%@",t_self.dataModel.time,t_self.dataModel.beginTime,t_self.dataModel.endTime];
            [self.tableView reloadData];
        };
    }
    return _timePicker2;
}

#pragma mark timePicker
- (AddressPicker *)timePicker
{
    if (!_timePicker) {
        _timePicker = [AddressPicker addressPickerView];
        _timePicker.delegate = self;
        _timePicker.dataSource = self;
        _timePicker.isLoding = NO;
        [_timePicker setTopHeadColor:NavBarTintColor];
        [_timePicker setTopTitle:@"选择时间段"];
        [_timePicker setTopTitleColor:[UIColor whiteColor]];
        [_timePicker setSureOrCancelBtnColor:[UIColor whiteColor]];
        _timePicker.bgColor = [UIColor clearColor];
        typeof(self) t_self = self;
        _timePicker.sureBtnClick = ^{
            //获取时间
            if (_selectRow == 0) {
//                [t_self.view endEditing:YES];
//                [t_self.timePicker1 showInView:t_self.view];
//                t_self.dataModel.time = [[NSDate date] getMyDateStrWithDateFormat:@"YYYY-MM-dd"];
                [t_self.view endEditing:YES];
                [t_self.timePicker1 showInView:t_self.view];
                t_self.dataModel.time = _timeArray[_selectRow];
            }else if (_selectRow == 1){
                [t_self.view endEditing:YES];
                [t_self.timePicker1 showInView:t_self.view];
                t_self.dataModel.time = _timeArray[_selectRow];
            }else if (_selectRow == 2){
                [t_self.view endEditing:YES];
                [t_self.timePicker1 showInView:t_self.view];
                t_self.dataModel.time = _timeArray[_selectRow];
            }else if (_selectRow == 3){
//                t_self.dataModel.time = _timeArray[_selectRow];
//                [self.tableView reloadData];
                [t_self.view endEditing:YES];
                [t_self.timePicker1 showInView:t_self.view];
                t_self.dataModel.time = _timeArray[_selectRow];
            }else if (_selectRow == 4){
                [t_self.view endEditing:YES];
                [t_self.datePicker showInWindow];
            }
            t_self.dataModel.timeType = _timeArray[_selectRow];
        };
    }
    return _timePicker;
}

- (NSInteger)numberOfComponentsInPickerView:(AddressPicker *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(AddressPicker *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView == self.timePicker) {
        return _timeArray.count;
    }else if (pickerView == self.timePicker1 || pickerView == self.timePicker2){
        return _timeArray1.count;
    }
    return 0;
    
}
- (nullable NSString *)pickerView:(AddressPicker *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView == self.timePicker) {
        return _timeArray[row];
    }else if (pickerView == self.timePicker1 || pickerView == self.timePicker2){
        return _timeArray1[row];
    }
    return nil;
}
- (void)pickerView:(AddressPicker *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView == self.timePicker) {
        _selectRow = (int)row;
    }else if (pickerView == self.timePicker1){
        _selectRow1 = (int)row;
    }else if (pickerView == self.timePicker2){
        _selectRow2 = (int)row;
    }
    
}

- (UIView *)pickerView:(AddressPicker *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view
{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:17]];
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}


- (IBAction)publishBtnClick:(id)sender {
    [self netWorking];
}
#pragma mark netWorking
- (void) netWorking
{
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"cityname"] = @"北京";
    postDict[@"createby"] = @"2";
    postDict[@"category"] = @"1";
    postDict[@"typeId"] = self.classifyId;
    postDict[@"chargeType"] = self.dataModel.isPay?@"2":@"1";
    postDict[@"servicePriceType"] = @"1";
    postDict[@"servicePrice"] = self.dataModel.isPay?self.dataModel.price:@"0";
    postDict[@"acceptableHours"] = self.dataModel.acceptableHours;
    postDict[@"destination"] = self.dataModel.address;
    postDict[@"inviteTimeRange"] = self.dataModel.timeType;
    postDict[@"inviteTimeRangeHours"] = [NSString stringWithFormat:@"%@-%@",self.dataModel.beginTime,self.dataModel.endTime];
    postDict[@"consumeType"] = self.dataModel.otherPay;
    postDict[@"sexLimit"] = [NSString stringWithFormat:@"%d",self.dataModel.sexType];
    postDict[@"ispickupWomen"] = self.dataModel.canShuttleWoman?@"0":@"1";
    postDict[@"isWithFriends"] = self.dataModel.womanTakeFriend?@"0":@"1";
    postDict[@"remark"] = self.dataModel.remark;
    [QLNetWorking postJSONWithUrl:QLPublishLifeInvitatURL parameters:postDict isJosnRequest:YES rogress:nil success:^(id result) {
        /*{
         mobileHead = {
         message = 发布成功;
         code = success;
         }
         ;
         mobileBody = {
         data = 7;
         }
         ;
         }*/
        if ([QLNetWorking sucess:[result objectForKey:@"mobileHead"] and:@"code" EqualToString:@"success"]) {
            NSString * data = [[result objectForKey:@"mobileBody"] objectForKey:@"data"];
            for (UIImage * ima in self.dataModel.imaArray) {
                [self publishSKillUpIma:data andIma:@[ima]];
            }
        }
    } fail:^(NSError *error) {
        
    }];
}
//上传图片，单张循环上传
- (void) publishSKillUpIma:(NSString *)skillId andIma:(NSArray<UIImage*> *)imaArray
{
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"userid"] = @"2";
    postDict[@"id"] = skillId;
    postDict[@"type"] = @"1";
    [QLNetWorking upImaWithURL:QLPublishLifeInvitImaURL parameters:postDict fieldName:@"file" andImas:imaArray success:^(id result) {
        NSLog(@"%@",result);
    } fail:^(NSError *error) {
        
    }];
}

- (void) netOtherPayTypeWorking
{
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc] init];
    postDict[@"pid"] = self.classifyId;
    [QLNetWorking postJSONWithUrl:QLPublishLifeOtherPayURL parameters:postDict isJosnRequest:YES rogress:nil success:^(id result) {
        NSLog(@"%@",result);
        if ([QLNetWorking sucess:[result objectForKey:@"mobileHead"] and:@"code" EqualToString:@"success"]) {
            _otherPayArray = [QLPublishLifeOtherPayModel mj_objectArrayWithKeyValuesArray:[[[result objectForKey:@"mobileBody"] objectForKey:@"data"] objectForKey:@"消费费用"]];
        }
    } fail:^(NSError *error) {
        
    }];
}


@end

